package com.bjtct.plugin.autogen.wizards;

import java.io.IOException;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import com.bjtct.plugin.autogen.db.DbFactory;
import com.bjtct.plugin.autogen.db.DbTable;
import com.bjtct.plugin.autogen.db.DbUtils;
import com.bjtct.plugin.autogen.db.IDataBase;

public class DataSourcePage extends WizardPage {

	private ISelection selection;
	private Text username;
	private Text pwd;
	private Combo combo;
	private Text host;
	private Text port;
	private Table table;
	private String dburl;
	private Text dbname;
	private String target;

	/**
	 * Create the wizard.
	 */
	public DataSourcePage() {
		super("wizardPage");
		setTitle("Wizard Page title");
		setDescription("Wizard Page description");
	}

	/**
	 * @wbp.parser.constructor
	 */
	public DataSourcePage(ISelection selection) {
		super("dspage");
		setDescription("设置数库连接，输入用户名，密码，连接串,数据库类型");
		setTitle("数据源设置");
		this.target = "";
		this.selection = selection;

	}

	/**
	 * Create contents of the wizard.
	 * 
	 * @param parent
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		Group dsgroup = new Group(container, SWT.NONE);
		dsgroup.setBounds(0, 0, 432, 75);
		dsgroup.setText("数据源设置");
		// 数据库连接相关设置
		Label label = new Label(dsgroup, SWT.NONE);
		label.setBounds(10, 20, 32, 23);
		label.setText("用户:");

		username = new Text(dsgroup, SWT.BORDER);
		username.setBounds(40, 20, 60, 20);

		Label label_1 = new Label(dsgroup, SWT.NONE);
		label_1.setBounds(106, 20, 32, 23);
		label_1.setText("密码:");

		pwd = new Text(dsgroup, SWT.BORDER | SWT.PASSWORD);
		pwd.setBounds(136, 20, 60, 20);

		Label label_2 = new Label(dsgroup, SWT.NONE);
		label_2.setBounds(10, 45, 32, 23);
		label_2.setText("主机:");

		host = new Text(dsgroup, SWT.BORDER);
		host.setBounds(40, 46, 60, 20);

		Label label_3 = new Label(dsgroup, SWT.NONE);
		label_3.setBounds(106, 49, 32, 23);
		label_3.setText("端口:");

		port = new Text(dsgroup, SWT.BORDER);
		port.setBounds(136, 46, 60, 20);

		Label label_4 = new Label(dsgroup, SWT.NONE);
		label_4.setBounds(202, 20, 39, 20);
		label_4.setText("类型:");

		combo = new Combo(dsgroup, SWT.NONE);
		combo.setItems(new String[] { "MYSQL", "ORACLE" });
		combo.setBounds(233, 17, 70, 22);

		Label lblNewLabel = new Label(dsgroup, SWT.NONE);
		lblNewLabel.setBounds(202, 46, 40, 23);
		lblNewLabel.setText("数据库:");

		dbname = new Text(dsgroup, SWT.BORDER);
		dbname.setBounds(243, 46, 60, 20);
		loadData();
		Button button = new Button(dsgroup, SWT.NONE);

		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				loadTable();

			}
		});
		button.setBounds(360, 35, 46, 27);
		button.setText("连接");

		// 表格显示，用于显示数据源连接成功后查询出来的所有表跟视图
		Group tbcomposite = new Group(container, SWT.NONE);
		tbcomposite.setBounds(10, 69, 422, 243);
		tbcomposite.setText("数据库表");
		table = new Table(tbcomposite, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION | SWT.V_SCROLL);
		table.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int select = table.getSelectionIndex();
				TableItem it = table.getItem(select);
				boolean ischeck = it.getChecked();
				int rows = table.getItemCount();
				if (ischeck) {
					it.setChecked(false);
				} else {
					it.setChecked(true);
					table.setSelection(select);
					target = it.getText(0);
					IDialogSettings dset = getSet();
					dset.put("selectTable", it.getText(0));
					saveDs(dset);
					reloadTableDetailPage();
				}
				if (table.getSelectionCount() == 0) {
					setErrorMessage("请选择一个表或视图再进行下一步操作!");
					setPageComplete(false);
				} else {
					setPageComplete(true);
				}
				for (int i = 0; i < rows; i++) {
					if (i != select) {
						table.getItem(i).setChecked(false);
					}
				}
			}
		});

		table.setBounds(10, 24, 402, 209);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setToolTipText("双击行显示详细设置");
		TableColumn head_name = new TableColumn(table, SWT.FILL);
		head_name.setText("名  称");
		head_name.setWidth(123);
		TableColumn head_type = new TableColumn(table, SWT.FILL);
		head_type.setText("类  型");
		head_type.setWidth(122);
		TableColumn head_mark = new TableColumn(table, SWT.FILL);
		head_mark.setText("备 注");
		head_mark.setWidth(133);
		if (target.length() == 0) {
			setMessage("选择要生成代码的表或视图!");
			setPageComplete(false);
		}
		setControl(container);

	}

	private void reloadTableDetailPage() {
		IWizardPage page = getNextPage();
		if (page.getControl() != null) {
			page.dispose();
		}
	}

	private void loadTable() {
		String dbuser = getUsername().getText();
		String dbpwd = getPwd().getText();
		String dbtype = getCombo().getText();
		String database = getDbname().getText();
		String dbhost = getHost().getText();
		String dbport = getPort().getText();
		if (DbUtils.isEmpty(dbuser) || DbUtils.isEmpty(dbpwd) || DbUtils.isEmpty(dbtype) || DbUtils.isEmpty(database)
				|| DbUtils.isEmpty(dbhost) || DbUtils.isEmpty(dbport)) {
			MessageDialog.openInformation(getShell(), "数据源", "数据源相关属性不能为空");
			return;
		}
		dburl = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + database;
		saveData(dbuser, dbpwd, dbtype, database, dbhost, dbport, dburl);
		IDataBase db = DbFactory.getDataBase(dbtype);
		table.removeAll();
		// 加载表格数据
		TableItem item = null;
		List<DbTable> list = db.getTables(dburl, getUsername().getText(), getPwd().getText(), getDbname().getText());
		for (DbTable t : list) {
			item = new TableItem(table, SWT.NONE);
			item.setText(new String[] { t.getName(), t.getType(), t.getMark() });
		}
	}

	private void saveData(String dbuser, String dbpwd, String dbtype, String database, String dbhost, String dbport,
			String url) {
		IDialogSettings dset = getSet();
		if (dset == null)
			return;
		dset.put("dbuser", dbuser);
		dset.put("dbpwd", dbpwd);
		dset.put("dbtype", dbtype);
		dset.put("database", database);
		dset.put("dbhost", dbhost);
		dset.put("dbport", dbport);
		dset.put("url", dburl);
		saveDs(dset);
	}

	private void saveDs(IDialogSettings dset) {
		try {
			dset.save("Tct.xml");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void loadData() {
		IDialogSettings dset = getSet();
		try {
			if (dset == null)
				return;
			dset.load("Tct.xml");
			// load from dset.xml
			String user = dset.get("dbuser");
			if (null != user) {
				username.setText(user);
			}
			String dbpwd = dset.get("dbpwd");
			if (null != dbpwd)
				pwd.setText(dbpwd);
			String dbtype = dset.get("dbtype");
			if (null != dbtype)
				combo.setText(dbtype);
			String database = dset.get("database");
			if (null != database)
				dbname.setText(database);
			String dbhost = dset.get("dbhost");
			if (null != dbhost)
				host.setText(dbhost);
			String dbport = dset.get("dbport");
			if (null != dbport)
				port.setText(dbport);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
	}

	private IDialogSettings getSet() {
		return getWizard().getDialogSettings();
	}

	public String getSelectTable() {
		String tb = null;
		int l = table.getSelectionIndex();
		TableItem it = table.getItem(l);
		if (it.getChecked())
			tb = it.getText(0);

		return tb;
	}

	public ISelection getSelection() {
		return selection;
	}

	public void setSelection(ISelection selection) {
		this.selection = selection;
	}

	public Text getUsername() {
		return username;
	}

	public void setUsername(Text username) {
		this.username = username;
	}

	public Text getPwd() {
		return pwd;
	}

	public void setPwd(Text pwd) {
		this.pwd = pwd;
	}

	public Text getHost() {
		return host;
	}

	public void setHost(Text host) {
		this.host = host;
	}

	public Text getPort() {
		return port;
	}

	public void setPort(Text port) {
		this.port = port;
	}

	public Table getTable() {
		return table;
	}

	public void setTable(Table table) {
		this.table = table;
	}

	public String getDburl() {
		return dburl;
	}

	public void setDburl(String dburl) {
		this.dburl = dburl;
	}

	public Combo getCombo() {
		return combo;
	}

	public void setCombo(Combo combo) {
		this.combo = combo;
	}

	public Text getDbname() {
		return dbname;
	}

	public void setDbname(Text dbname) {
		this.dbname = dbname;
	}

}
